import ccclass = cc._decorator.ccclass;
import property = cc._decorator.property;

/**
 * 排行榜数据过期方式.
 */
enum DateFilter {
    NONE = 0, WEEK = 1, MONTH = 2
}

// @ts-ignore
const wx: any = window.wx || false;
const contextList: Array<SubContextView> = [];

@ccclass
export class SubContextView extends cc.Component {
    private sprite: cc.Sprite = null;
    private readonly texture: cc.Texture2D = new cc.Texture2D();

    // 用于表示当前子域需要绘制哪个View.
    @property
    public readonly viewName: string = "";

    // 约定要获取的key的名称.即 getCloudStorage(keyList:key)
    @property
    public readonly key: string = "";

    // 用于表示子域数据根据什么key 进行排行.
    @property
    public readonly sortKey: string = "";

    @property({
        type: cc.Enum(DateFilter),
        serializable: true,
        displayName: "过滤方式",
        tooltip: "指定排行数据是否按周/月进行过滤,仅显示本周/月的数据."
    })
    private dateFilter: DateFilter = DateFilter.NONE;

    public onLoad() {
        this.sprite = this.getComponent(cc.Sprite);
        if (!this.sprite) {
            this.sprite = this.addComponent(cc.Sprite);
        }

    }

    public start() {
    }

    public onEnable() {
        if (!wx) {
            return;
        }
        if (this.viewName.length <= 0 || this.key.length <= 0) {
            console.error("SubContextView 未设置子域viewName 和key,无法显示子域");
            return;
        }

        contextList.forEach(item => {
            item.enabled = false;
        });
        contextList.push(this);

        cc.log("SubContextView 显示子域:", this.viewName, this.key);
        const shareCanvas = this.getShareCanvas();
        shareCanvas.width = this.node.width;
        shareCanvas.height = this.node.height;
        this.sendMsgToContext("action_init_context", {view: this.viewName, bound: this.node.getContentSize()});
        console.log("SubContextView onEnable.");
        // this.schedule(this.render, 0.2, cc.macro.REPEAT_FOREVER);
        this.updateView();
        this.setPage(0);
    }

    public onDisable() {
        const index = contextList.indexOf(this);
        if (index >= 0) {
            contextList.splice(index, 1);
        }
        if (contextList.length > 0) {
            contextList[contextList.length - 1].enabled = true;
        }
    }

    public updateView() {
        this.sendMsgToContext(this.viewName, {sortKey: this.sortKey, key: this.key, dateFilter: this.dateFilter});
    }

    public setPage(page: number) {
        this.sendMsgToContext("action_paging", {page: page, view: this.viewName});
    }

    // 向前翻页.
    public pageUp() {
        this.sendMsgToContext("action_paging", {offset: -1, view: this.viewName});
    }

    // 向后翻页.
    public pageDown() {
        this.sendMsgToContext("action_paging", {offset: 1, view: this.viewName});
    }

    public lateUpdate() {
        this.render();
    }

    // 强制刷新View.
    public refresh() {
        this.enabled = true;
        // if (this.sprite.spriteFrame) {
        //     this.sprite.spriteFrame = new cc.SpriteFrame();
        // }
        // this.render();
    }

    // 上传微信子域排行数据,可直接在主域中使用.
    public static updateUserData(key: string, data: any, sortKey?: string): Promise<any> {
        if (!wx) {
            return Promise.resolve();
        }
        if (!key || !data) {
            return;
        }
        return new Promise<any>((resolve, reject) => {
            // 为data自动增加一个uuid, 用来进行自身数据的查找. 否则不知道排行中哪一条是自己.
            data.uuid = "" + Math.random();

            // 增加时间戳,用来进行排行数据过滤.
            data.timestamp = cc.sys.now();

            // 增加小游戏中心排行显示.
            if (sortKey) {
                data.wxgame = {score: data[sortKey], update_time: data.timestamp}
            }
            wx.setUserCloudStorage({
                KVDataList: [{
                    key: key,
                    value: JSON.stringify(data)
                }],
                success: function (args) {
                    cc.log("上传排行榜成功.", args);
                    resolve(args);
                },
                fail: function (args) {
                    cc.log("上传排行榜失败.", args);
                    reject(args);
                }
            })
        })
    }

    private render() {
        if (!wx) {
            return;
        }
        const shareCanvas = this.getShareCanvas();
        this.texture.initWithElement(shareCanvas);
        this.texture.handleLoadedTexture();
        this.sprite.spriteFrame = new cc.SpriteFrame(this.texture);
        // if (!this.sprite.spriteFrame) {
        //     this.sprite.spriteFrame = new cc.SpriteFrame(this.texture);
        // } else {
        //     this.sprite.spriteFrame.setTexture(this.texture);
        // }
    }

    private getShareCanvas(): any {
        if (!wx) {
            return false
        }
        const context = wx.getOpenDataContext();
        return context.canvas
    }

    // 向子域同步指令.
    private sendMsgToContext(what: number | string, args: any) {
        const context = wx && wx.getOpenDataContext();
        if (!context) {
            console.info("微信环境异常.无法调用context.");
            return
        }
        context.postMessage({what, arguments: args});
    }
}
